package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.payment.service.AccountPayService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/***
 * 账户余额扣款service实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AccountPayServiceImpl implements AccountPayService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Resource
    private UserAccountFeignClient userAccountFeignClient;

    /**
     * 获取账户余额支付url
     *
     * @param params
     * @return
     */
    @Override
    public String getPayInfoFromAccount(Map<String, String> params) {
        // 从注册中心获取service-payment实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("service-payment");
        // 拼接通知地址
        String notifyUrl = serviceInstance.getUri().toString() + "/api/payment/accountPay/accountNotifyAddress";
        // 参数存入通知地址
        params.put("notifyUrl", notifyUrl);
        // userAccountFeign调用获取余额支付地址
        Result result = userAccountFeignClient.getPayInfo(params);
        // 判断getPayInfo调用结果
        if (result.getCode().equals(ResultCodeEnum.SUCCESS.getCode())) {
            // 若调用成功 则返回余额支付的url
            return String.valueOf(result.getData());
        }
        return null;
    }
}
